<template>
    <div>
        <el-dialog v-model="props.isShow" :title="props.isAdd ? '添加商品' : '编辑商品'" :before-close="closeX"
            @open="open(formRef)">
            <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">

                <el-form-item label="一级分类" prop="first_cateid">
                    <el-select v-model="form.first_cateid" placeholder="请选择一级分类" @change="change1(true)">
                        <el-option v-for="item in store.getters['cate/getCate']" :key="item.id" :label="item.catename"
                            :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="二级分类" prop="second_cateid">
                    <el-select v-model="form.second_cateid" placeholder="请选择二级分类">
                        <el-option v-for="item in cateArr" :key="item.id" :label="item.catename" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="商品名称">
                    <el-input v-model="form.goodsname" />
                </el-form-item>

                <el-form-item label="价格" prop="price">
                    <el-input v-model="form.price" />
                </el-form-item>

                <el-form-item label="市场价格" prop="market_price">
                    <el-input v-model="form.market_price" />
                </el-form-item>

                <el-form-item label="图片">
                    <el-upload class="avatar-uploader" action="#" :file-list="photo" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-change="changeInfo"
                        :limit="1">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>


                <el-form-item label="商品规格" prop="specsid">
                    <el-select v-model="form.specsid" placeholder="请选择商品规格" @change="change2(true)">
                        <el-option v-for="item in specsList" :key="item.id" :label="item.specsname" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="规格属性" prop="specsattr">
                    <el-select v-model="form.specsattr" placeholder="请选择规格属性" multiple>
                        <el-option v-for="item in specsArr" :key="item.id" :label="item" :value="item" />
                    </el-select>
                </el-form-item>

                <el-form-item label="是否新品">
                    <el-radio-group v-model="form.isnew">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="2">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="是否热卖">
                    <el-radio-group v-model="form.ishot">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="2">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="状态">
                    <el-switch v-model="form.status" :active-value="1" :inactive-value="2"></el-switch>
                </el-form-item>

                <el-form-item label="商品描述" id="edit">

                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="close()">取消</el-button>
                    <el-button type="primary" @click="submit(formRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, FormRules, FormInstance } from 'element-plus'
import { ref, reactive, defineProps, defineEmits,defineExpose } from "vue";
import { useStore } from 'vuex';
import { specslist, goodsadd, goodsedit,goodsinfo } from '@/request/api';
let store = useStore()
let formRef = ref<FormInstance>()
let emit = defineEmits(['close'])

let cateArr = ref()
let specsArr = ref()
let specsList = ref()



// 关闭
let close = () => {
    emit("close")
}

const closeX = (done: any) => {
    done()
    close()
}

let open = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    form.value = {
        first_cateid: "",//一级分类编号
        second_cateid: "",//二级分类编号
        goodsname: "",//商品名称
        price: "",//商品价格
        market_price: "",//市场价格
        img: [],//商品图片（文件）
        description: "",//商品描述
        specsid: "",//商品规格编号
        specsattr: [],//商品规格属性
        isnew: 1,//是否新品 1-是 2-否
        ishot: 1,//是否热卖推荐 1-是 2-否
        status: 1,//状态1正常2禁用
        id:0

    }
    formEl.resetFields();
    imageUrl.value = ''
}

let submit = async (formEl: FormInstance | undefined) => {
    form.value.specsattr = form.value.specsattr.join(",")
    if (!formEl) return
    await formEl.validate((val) => {
        if (val) {
            if (props.isAdd) {
                goodsadd(form.value).then((res: any) => {
                    if (res.code == 200) {
                        get()
                        close()

                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            } else {
                goodsedit(form.value).then((res: any) => {
                    if (res.code == 200) {
                        get()
                        close()
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })

            }

        }
    })
}

let change1 = (n: Boolean) => {
    let index = store.getters['cate/getCate'].findIndex((item: any) => {
        return item.id == form.value.first_cateid
    })
    cateArr.value = store.getters['cate/getCate'][index].children
    if (n) {
        form.value.second_cateid = ""
    }
}

let change2 = (n: Boolean) => {
    let index = specsList.value.findIndex((item: any) => {
        return item.id == form.value.specsid
    })
    specsArr.value = specsList.value[index].attrs
    if (n) {
        form.value.specsattr = []
    }
}


let props = defineProps({
    isAdd: Boolean,
    isShow: Boolean
})

let form = ref({
    first_cateid: "",//一级分类编号
    second_cateid: "",//二级分类编号
    goodsname: "",//商品名称
    price: "",//商品价格
    market_price: "",//市场价格
    img: [],//商品图片（文件）
    description: "",//商品描述
    specsid: "",//商品规格编号
    specsattr: [],//商品规格属性
    isnew: 1,//是否新品 1-是 2-否
    ishot: 1,//是否热卖推荐 1-是 2-否
    status: 1,//状态1正常2禁用
    id:0

})

let get = () => {
    store.dispatch("cate/getCateListAction")
    store.dispatch("specs/getSpecsListAction")
    store.dispatch("goods/getCountAction")
    store.dispatch("goods/getGoodsInfoActions")

}
get()

let getList = () => {
    specslist(null).then((res: any) => {
        specsList.value = res.list
    })
}

getList()

let lookup = (id:number) =>{
    goodsinfo({id}).then((res:any)=>{
        console.log(res);
        form.value = res.list
        form.value.specsattr = res.list.specsattr.split(",")
        imageUrl.value = res.list.img
        form.value.id = id
        change1(false)
        change2(false)
        
    })
    

}
defineExpose({
    lookup
})



// 图片上传
let photo = ref()
const imageUrl = ref('')
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}
let changeInfo = (file: any) => {
    form.value.img = file.raw
}

// 正则验证
let rules = reactive<FormRules>({
    price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
    market_price: [
        { required: true, message: "请输入市场价格", trigger: "blur" },
    ],
    first_cateid: [
        { required: true, message: "请选择一级分类", trigger: "change" },
    ],
    second_cateid: [
        { required: true, message: "请选择二级分类", trigger: "blur" },
    ],
    specsid: [
        { required: true, message: "请选择商品规格", trigger: "change" },
    ],
    specsattr: [
        { required: true, message: "请选择规格属性", trigger: "blur" },
    ],
})

</script>


<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>